// 导入 express
const express = require('express')
// 创建服务器的实例对象
const app = express()
// 导入并配置 cors 中间件
const cors = require('cors')
app.use(cors())


const usersql = require('./mysql.js')
usersql.connect()

// 配置req.body的组件
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

// 配置解析jwt组件
const config = require('./config.js')
const expressJWT = require('express-jwt')
const whileArr = ['/api/api/login', '/api/hold/imgload', '/api/hold/img', '/api/hold/imgdownload', 
'/api/admin/finduser', '/api/admin/adduser', '/api/admin/user','/api/postdata','/api/getdata','/api/getstatus']
app.use(expressJWT({ secret: config.secretKey }).unless({ path: whileArr }))

// 封装res.cc函数 发送错误信息
app.use((req, res, next) => {
    res.cc = (err, status = 1) => {
        res.send({
            status,
            // 判断message是否为构造函数实例
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 连接websocket服务   9191端口
const WebSockets = require('ws') 
const { WebSocketConnect } = require('./websocket.js')
const ws = new WebSockets.Server({ port: 9191 })
ws.on('connection', WebSocketConnect)

// 导入并使用用户路由模块

const userRouter = require('./router/index.js')
app.use('/api', userRouter)

// 导入错误级别中间件
const Joi = require('joi')
app.use((err, req, res, next) => {
    console.log(err)
    if (err instanceof Joi.ValidationError) return res.cc(err)
    res.send({
        status: 1,
        // 判断message是否为构造函数实例
        message: err instanceof Error ? err.message : err
    })
})
app.listen(8191, () => {
    console.log('Service running on port 8191')
})